﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Asah.SiteWorx.Commerce
{
    [Serializable()]
    public class ShoppingCart
    {
        private List<CartItem> _cartItems = new List<CartItem>();

        public List<CartItem> CartItems
        {
            get
            {
                return _cartItems;
            }
        }

        public void AddToCart(string itemNumber, string productTitle, int quantity, decimal unitPrice)
        {
            
            //first need to check and see if the item is already in the cart otherwise we create a
            //new cart item and add it to the shopping cart.
            CartItem item = FindCartItem(itemNumber);

            if (item == null)
            {
                item = new CartItem(itemNumber, productTitle, unitPrice, quantity);
                _cartItems.Add(item);
            }
            else
                item.Quantity += quantity;
            
        }

        public void UpdateCart(string itemNumber, int quantity)
        {
            CartItem item = FindCartItem(itemNumber);

            if (item != null)
                item.Quantity = quantity;
        }

        private CartItem FindCartItem(string itemNumber)
        {
           foreach (CartItem item in _cartItems)
            {
                if (item.ItemNumber == itemNumber)
                {
                    return item;
                }
            }
            return null;
        }

        public decimal GetCartTotal()
        {
            decimal grandTotal = 0;
            foreach (CartItem item in _cartItems)
            {
                grandTotal += item.Total;
            }
            return grandTotal;
        }

        public int GetCartQuantity()
        {
            int total = 0;
            foreach (CartItem item in _cartItems)
            {
                total += item.Quantity;
            }
            return total;
        }

        public Order CreateOrder()
        {
            Order order = null;
            if (_cartItems.Count > 0)
            {
                order = Order.NewOrder();

                OrderItem orderItem = null;
                foreach (CartItem item in _cartItems)
                {
                    orderItem = order.OrderItems.AddNew();
                    orderItem.ItemNumber = item.ItemNumber;
                    orderItem.ProductTitle = item.ProductTitle;
                    orderItem.UnitPrice = item.UnitPrice;
                    orderItem.Quantity = item.Quantity;
                }
            }
            return order;
        }
    }
}
